#ifndef __POLL_SVR_H__
#define __POLL_SVR_H__

#include <iostream>
#include <poll.h>
#include <sys/time.h>
#include <string>
#include "Log.hpp"
#include "Sock.hpp"


#define FD_NONE -1 // 表示初始化状态

using namespace std;

// 使用select进行监控，对多个文件描述符进行管理

class pollServer
{
public: 
    static const int nfds = 100;

public:
    pollServer(const uint16_t &port = 8080)
        : _port(port), _nfds(nfds)
    {
        _listensock = Sock::Socket();
        Sock::Bind(_listensock, _port);
        Sock::Listen(_listensock);
        logMessage(DEBUG, "%s", "create base socket success");

        _fds=new struct pollfd[_nfds];
        for(int i=0; i<_nfds; i++) {
            _fds[i].fd=FD_NONE;
            _fds[i].events=_fds[i].revents=0;
        }
        _fds[0].fd=_listensock;
        // _fds[0].events=POLLIN | POLLOUT;
        _fds[0].events=POLLIN;
        _timeout=1000;
    }

    void Start()
    {
       while (true)
        {

            int n = poll(_fds,_nfds,_timeout);
            switch (n)
            {
            case 0:
                logMessage(DEBUG, "%s", "time out...");
                break;
            case -1:
                logMessage(WARNING, "select error:%d: %s", errno, strerror(errno));
                break;
            default:                                           
            // 成功
                HandlerEvent();
                break;
            }
        }
    }

    ~pollServer()
    {
        if (_listensock >= 0)
            close(_listensock);
        if(_fds) delete[] _fds;
    }

private:
    void HandlerEvent() // fd_set 是一个集合，可能有多个sock
    {
        for (int i = 0; i < _nfds; i++)
        {
            // 去掉不合法的fd
            if (_fds[i].fd == FD_NONE)
                continue;
            // 合法不一定就绪了
            if (_fds[i].revents & POLLIN)
            {
                // 指定的fd， 读事件就绪
                if (_fds[i].fd == _listensock)
                {
                    // 读事件就绪，连接事件到来，accepter
                    Accepter();
                }
                else
                {
                    // 读事件就绪：input事件到来，recv，read
                    Recver(i);
                }
            }
        }
    }

    void Accepter() // 获取新连接
    {
        string clientip;
        uint16_t clientport = 0;
        // listensock上面的读事件就绪，可以进行读取了
        // 获取新连接
        int sock = Sock::Accept(_listensock, &clientip, &clientport); // 不会造成阻塞
        if (sock < 0)
        {
            logMessage(WARNING, "accept error");
            return;
        }
        logMessage(DEBUG, "get a new line success : [%s : %d] %d ", clientip.c_str(), clientport, sock);

        int pos = 1;
        for (; pos < _nfds; pos++)
        {
            if (_fds[pos].fd == FD_NONE)
                break;
        }
        if (pos == _nfds)
        {
            logMessage(WARNING, "%s:%d", "poll server already full, close: %d", sock);
            close(sock);
        }
        else
        {
            _fds[pos].fd = sock;
            _fds[pos].events = POLLIN;
        }
    }

    void Recver(int pos)
    {

        logMessage(DEBUG, "message in, get IO event: %d", _fds[pos]);
        // fd上的数据一定是就绪的，即 本次 不会被阻塞

        /********不能保证一定会读到一个完整的报文，存在bug********/
        char buffer[1024];
        int n = recv(_fds[pos].fd, buffer, sizeof(buffer - 1), 0);
        if (n > 0)
        {
            buffer[n] = 0;
            logMessage(DEBUG, "client[%d]# %s", _fds[pos].fd, buffer);
        }
        /*****************************************/
        else if (n == 0) // 连接关闭,退出
        {
            logMessage(DEBUG, "client[%d] quit, me too...", _fds[pos].fd);
            // 关闭fd
            close(_fds[pos].fd);
            // 置-1
            _fds[pos].fd = FD_NONE;
            _fds[pos].events =0;
        }
        else
        {
            logMessage(WARNING, "%d sock recv error, %d: %s", _fds[pos].fd, errno, strerror(errno));
            // 关闭fd
            close(_fds[pos].fd);
            // 置-1
            _fds[pos].fd = FD_NONE;
            _fds[pos].events =0;
        }
    }



    void debugPrint()
    {
        cout << "_fd_array[]: ";
        for (int i = 0; i < _nfds; i++)
        {
            if (_fds[i].fd == FD_NONE)
                continue;
            cout << _fds[i].fd << " ";
        }
        cout << endl;
    }

private:
    uint16_t _port;
    int _listensock;
    struct pollfd *_fds;
    int _nfds;
    int _timeout;
};

#endif